package org.research.util;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import javax.swing.ImageIcon;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

/** 工具类 */
public class Tools {
	// 创建日期格式
	private static SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
	// 创建中国的货币格式
	private static NumberFormat currencyFormat = NumberFormat
			.getCurrencyInstance(Locale.CHINA);

	/** FCKeditor内置的分页字符串 */
	private static String fck_separator = "<div style=\"PAGE-BREAK-AFTER: always\"><span style=\"DISPLAY: none\">&nbsp;</span></div>";

	/** 取得指定图片的宽度与高度 */
	public static Map<String,Integer> getPicWidthHeight(String filename) {
		Map<String,Integer> map = new HashMap<String,Integer>();
		try {
			BufferedImage sourceImg = javax.imageio.ImageIO
					.read(new FileInputStream(filename));
			map.put("width", sourceImg.getWidth());
			map.put("height", sourceImg.getHeight());
			return map;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	/** 取得随机主文件名 */
	public synchronized static String getRndFilename() {
		return String.valueOf(System.currentTimeMillis());
	}

	/** 取得指定文件的文件扩展名 */
	public synchronized static String getFileExtName(String filename) {
		//int p = filename.indexOf(".");
		int p = filename.lastIndexOf(".");
		return filename.substring(p);
	}

	/** 验证上传文件的类型是否合法 fileType:1-图片 2-视频 */
	public synchronized static boolean isEnableUploadType(int fileType,
			String filename) {
		String enableExtNames = null;
		int p = filename.indexOf(".");
		String fileExtName = filename.substring(p).toLowerCase();
		if (fileType == 1) {// 图片文件类型
			enableExtNames = ".jpg,.gif,.png";
		} else if (fileType == 2) {// 视频文件类型
			enableExtNames = ".flv";
		}
		if (enableExtNames != null) {
			if (enableExtNames.indexOf(fileExtName) != -1)
				return true;
			else
				return false;
		} else {
			return true;
		}

	}

	/** HTML代码的Escape处理方法 */
	public static String escape(String src) {
		int i;
		char j;
		StringBuffer tmp = new StringBuffer();
		tmp.ensureCapacity(src.length() * 6);
		for (i = 0; i < src.length(); i++) {
			j = src.charAt(i);
			if (Character.isDigit(j) || Character.isLowerCase(j)
					|| Character.isUpperCase(j))
				tmp.append(j);
			else if (j < 256) {
				tmp.append("%");
				if (j < 16)
					tmp.append("0");
				tmp.append(Integer.toString(j, 16));
			} else {
				tmp.append("%u");
				tmp.append(Integer.toString(j, 16));
			}
		}
		return tmp.toString();
	}

	/** HTML代码的UnEscape处理方法 */
	public static String unescape(String src) {
		StringBuffer tmp = new StringBuffer();
		tmp.ensureCapacity(src.length());
		int lastPos = 0, pos = 0;
		char ch;
		while (lastPos < src.length()) {
			pos = src.indexOf("%", lastPos);
			if (pos == lastPos) {
				if (src.charAt(pos + 1) == 'u') {
					ch = (char) Integer.parseInt(src
							.substring(pos + 2, pos + 6), 16);
					tmp.append(ch);
					lastPos = pos + 6;
				} else {
					ch = (char) Integer.parseInt(src
							.substring(pos + 1, pos + 3), 16);
					tmp.append(ch);
					lastPos = pos + 3;
				}
			} else {
				if (pos == -1) {
					tmp.append(src.substring(lastPos));
					lastPos = src.length();
				} else {
					tmp.append(src.substring(lastPos, pos));
					lastPos = pos;
				}
			}
		}
		return tmp.toString();
	}

	/** 为以逗号分隔的字符串的每个单元加入引号,如:aa,bb-->'aa','bb' */
	public static String formatString(String src) {
		StringBuffer result = new StringBuffer();
		result.append("");
		if (src != null) {
			String[] tmp = src.split(",");
			result.append("'" + tmp[0] + "'");
			for (int i = 1; i < tmp.length; i++) {
				result.append(",'" + tmp[i] + "'");
			}
		}
		return result.toString();
	}

	/** 截取指定字节数的字符串,且确保汉字不被拆分 */
	public static String cutString(String text, int textMaxChar) {
		int size, index;
		String result = null;
		if (textMaxChar <= 0) {
			result = text;
		} else {
			for (size = 0, index = 0; index < text.length()
					&& size < textMaxChar; index++) {
				size += text.substring(index, index + 1).getBytes().length;
			}
			result = text.substring(0, index);
			if(text.getBytes().length>textMaxChar){
				result = result + "...";
			}
		}
		return result;
	}

	/** 按yyyy-MM-dd格式格式化日期 */
	public static String formatDate(Date date) {
		if (date == null) {
			return "";
		} else {
			return df.format(date);
		}
	}

	/** 对未escape的HTML内容进行FCK分页处理,返回String[] */
	public static String[] splitContent(String unEscapedHtml) {
		if (unEscapedHtml == null) {
			return null;
		} else {
			return unescape(unEscapedHtml).split(fck_separator);
		}
	}

	/** 取得格式化后的中国货币字符串 */
	public static String formatCcurrency(double money) {
		return currencyFormat.format(money);

	}

	/** 生成一定数量的字符串 */
	public static String createString(int number) {
		StringBuffer str = new StringBuffer();
		for (int i = 0; i < number; i++) {
			str.append("0");
		}
		return str.toString();
	}

	/** 检测系统登录用户是否含有导航菜单权限 */
	public static boolean checkMenuGrant(String userGrant, int grantId) {
		boolean result = false;
		if (userGrant.length() >= grantId) {
			if (userGrant.substring(grantId - 1, grantId).equals("1")) {
				result = true;
			}
		}
		return result;
	}

//	public static void main(String[] args) {
//		//System.out.println(Tools.checkMenuGrant("00000010000000001001", 8));
//		createFloatPic("关于2013年表彰服务小微企业和三农双二十佳金融产品的决定关于表彰服务小微企业和三农双二十佳金融产品的决定",18);
//	}
	
	
	/**
	 * CKEditor中的url和img
	 */
	public static int checkImgAndCNWord(String strContent,int intPos,StringBuilder sbImgUrl,StringBuilder sbDes){
		
		int intResult = intPos;
		int intIndexOfImg1 =  strContent.indexOf("<img",intPos);
		if(intIndexOfImg1 != -1) {
			int intIndex = strContent.indexOf("src", intIndexOfImg1 + 4);
			if(intIndex != -1) {
				// 找出img的路徑
				while(intIndex < strContent.length() && strContent.charAt(intIndex++) != '"' );
				int intTempBegin = intIndex;
				while(intIndex < strContent.length() && strContent.charAt(intIndex++) != '"' );
				// 截出img的路徑
				String strImgUrl = strContent.substring(intTempBegin,intIndex - 1 );
				//System.out.println("图片url是:" + strImgUrl);
				sbImgUrl.append(strImgUrl);
				// 找出图片描述
				intIndex = strContent.indexOf("/>", intIndex);
				// 下一个图片位置
				int intIndexOfImg2 = strContent.indexOf("<img", intIndex+2);
				intResult = intIndexOfImg2;
				if(intIndexOfImg2 != -1) {
					String strDes = strContent.substring(intIndex+2, intIndexOfImg2);
					// 对字符串进行清理
					strDes = swapString(strDes);
					if(!"".equals(strDes)) {
						//System.out.println("图片描述是："+ strDes);
						sbDes.append(strDes);
					} else {
						//System.out.println("图片描述是：没有图片描述");
						sbDes.append("");
					}
					
				} else {
					tailProcessor(strContent,intIndex + 2,sbImgUrl, sbDes);
				}
				
			} else {
				intResult = -1;
			}
		} else {
			intResult = -1;
		}
		
		return intResult;
	}
	
	/**
	 * 这是后面没有img的情况
	 */
	private static void tailProcessor(String strContent, int intTempPos,StringBuilder sbImgUrl,StringBuilder sbDes){

		String strTempDes = "";
		int intAvoidCycle = 0;
		do{
			int intIndexOfBr1 = strContent.indexOf("<br />",intTempPos);
			if(intIndexOfBr1 != -1){
				// 提取两个字符串之间的内容，判断是否是描述内容
				int intIndexOfBr2 = strContent.indexOf("<br />",intIndexOfBr1 + 6);
				if(intIndexOfBr2 == -1) {
					// 截取intIndexOfBr1 到字符串结尾的内容
					strTempDes = strContent.substring(intIndexOfBr1, strContent.length());
					strTempDes = swapString(strTempDes);
					if(!"".equals(strTempDes)){
						//System.out.println("图片描述是：" + strTempDes);
						sbDes.append(strTempDes);
					}
					break;
				} else {
					// 截取 intIndexOfBr1 到 intIndexOfBr2的内容
					strTempDes = strContent.substring(intIndexOfBr1,intIndexOfBr2);
					strTempDes = swapString(strTempDes);
					intTempPos = intIndexOfBr2;
					if(!strTempDes.equals("")){
						//System.out.println("图片描述是：" + strTempDes);
						sbDes.append(strTempDes);
					}
				}
			}  else {
				// 截取 intIndexOfBr1 到 最后的内容
				strTempDes = strContent.substring(intTempPos,strContent.length());
				strTempDes = swapString(strTempDes);
				if(!strTempDes.equals("")){
					//System.out.println("图片描述是：" + strTempDes);
					sbDes.append(strTempDes);
				}
				break;
			}
			// 防止出现死循环
			if(intAvoidCycle++ >15){
				//System.out.println("+++++++++++++++++++++++");
				//System.out.println("出现死循环");
				//System.out.println("+++++++++++++++++++++++");
				break;
			}
			
		} while("".equals(strTempDes) && intTempPos < strContent.length());
		if("".equals(strTempDes)){
			//System.out.println("图片描述是：无图片描述");
			sbDes.append("");
		}
	}
	
	/**
	 * 清洗字符串，去掉html标记
	 */
	private static String swapString(String strOri){

		return strOri.replaceAll("(<[a-z|A-Z]+[ |\"|[a-z|A-Z|/|=|\\|.|[0-9]]]*>)|(</[a-z|A-Z]+>)|(&nbsp;)","").trim();
	}
	
	/**
	 * 生成飘窗图片
	 */
	public static String createFloatPic(String contextPath,String markContent,Integer wordsNum){
		
			//System.out.println("开始生成图片");
		   //String filePath = "D://fwTemplet.jpg";
		   String filePath = contextPath + "fwTemplet.jpg";
		   Date date = new Date();
		   String filePath1 = "D://flt_" + date.getTime() + ".jpg";
		   Color markContentColor = new Color(245,6,6);
		   ImageIcon imgIcon = new ImageIcon(filePath);  
		   Image theImg = imgIcon.getImage();  
		   //Image可以获得 输入图片的信息  
		   int width = theImg.getWidth(null);
		   int height = theImg.getHeight(null);  
		    
		   //800 800 为画出图片的大小 TYPE_INT_RGB TYPE_BYTE_BINARY
		   BufferedImage bimage = new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB);  
		   //2d 画笔  
		   Graphics2D g = bimage.createGraphics();  
		   g.setColor(markContentColor);
		   g.setBackground(Color.white);
		    
		   //画出图片-----------------------------------  
		   g.drawImage(theImg, 0, 0, null);  
		   //画出图片-----------------------------------  
		    
		    
		   //--------对要显示的文字进行处理--------------  
		  // markContent = "关于2013年表彰服务小微企业和三农双二十佳金融产品的决定关于表彰服务小微企业和三农双二十佳金融产品的决定";// 文字  
//		   AttributedString ats = new AttributedString(markContent);  
		   Font f = new Font("宋体", Font.PLAIN, 12);  
		   //ats.addAttribute(TextAttribute.FONT, f, 0, markContent.length());  
		   //AttributedCharacterIterator iter = ats.getIterator();
		   //----------------------  
		    
		   //g.drawString(iter, (int) (width - width+10), (int) (height - height/2));
		   g.setFont(f);
		   if(markContent.length()<=wordsNum){
				g.drawString(markContent, 21,44);// 写入签名  
			} else {
				String strInfo1 = markContent.substring(0,wordsNum);
				String strInfo2 = "";
				if(markContent.length()> wordsNum*2){
					if(wordsNum * 2 > 3){
						strInfo2 = markContent.substring(wordsNum,wordsNum * 2-3);
						strInfo2 = strInfo2 + "...";
					}
				} else {
					strInfo2 = markContent.substring(wordsNum,markContent.length());
				}
				g.drawString(strInfo1, 22,44);// 写入签名  
				// + 22
				g.drawString(strInfo2, 22,66);// 写入签名  
			}
		   //g.drawString(iter, 22, 44);
		   //添加水印的文字和设置水印文字出现的内容 ----位置  
		   g.dispose();//画笔结束  
		   try {  
		    //输出 文件 到指定的路径  
		    FileOutputStream out = new FileOutputStream(filePath1);  
		    JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
		    JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bimage); 
		    param.setQuality(1.0f, true);  
		    encoder.encode(bimage, param);  
		    out.close();  
		    //System.out.println("成功生成图片");
		   } catch (Exception e) {  
			   filePath1 = null;
			   //System.out.println("生成图片失败");
		   }  
		   
		   return filePath1;  
		}  
	
}
